<template>
  <div class="dashboard-container">
    <el-row :gutter="20" justify="space-between" style="margin-bottom: 20px">
      <el-col :xs="{span: 24}" :sm="{span: 24}" :md="{span: 16}" :lg="{span: 16}" :xl="{span: 16}">
        <el-card shadow="always">
          <el-skeleton :loading="loading" :rows="3" animated>
            <el-row :gutter="20">
              <el-col :span="1.5">
                <img :src="getImageSrc(user.avatar)" style="width: 100px; height: 100px; border-radius: 45%">
              </el-col>
              <el-col :span="1.5">
                <div style="font-size: 20px; font-weight: bold; margin-bottom: 20px;">
                  {{ new Date() | parseTimeState(user.userName) }}
                </div>
                <el-alert
                  title="挫折是一块石头，对于弱者来说它是拌脚石，让你停步不前。而对于强者来说它是垫脚石，使你站得更高。希望每个人，无论过程怎样，结局都是美好的。。。"
                  :closable="false"
                >
                  <a
                    target="_blank"
                    href="https://gitee.com/zy0fy/piece-single"
                  ><el-link type="success">vue-piece-admin</el-link></a>
                </el-alert>
              </el-col>
            </el-row>
          </el-skeleton>
        </el-card>

        <el-skeleton :loading="loading" :rows="6" animated>
          <el-card shadow="hover" style="margin:20px 0 5px 5px">
            <el-form ref="queryForm" :inline="true" :model="queryData">
              <el-form-item prop="selBLine">
                <el-input v-model="queryData.selBLine" placeholder="公交线路" @blur="changeBLine" />
              </el-form-item>
              <el-form-item>
                <el-select v-model="queryData.selBDir" placeholder="请选择线路方向" @change="changeBdir">
                  <el-option
                    v-for="item in selBDirs"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-select v-model="queryData.selBStop" placeholder="请选择站点">
                  <el-option
                    v-for="item in selBStops"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item class="fr p-r-10">
                <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="changeBStop">
                  搜索
                </el-button>
              </el-form-item>
            </el-form>
            <div ref="busTimeInfo" style="overflow-x: auto" />
          </el-card>
          <baidu-map :style="'{width: 100%; height: ' + mapHeight + 'px;}'" ak="Ykv5kItIHoOtTfK7VNkY1E0MbHpwq8Xm" :center="center" :zoom="zoom" :scroll-wheel-zoom="false" @ready="handlerInitMap">
            <bm-control>
              <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 1 }">
                <el-input v-model="keyword" placeholder="请输入地名关键字" />
              </bm-auto-complete>
            </bm-control>
            <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT" />
            <bm-local-search :keyword="keyword" :auto-viewport="true" />
            <bm-bus :keyword="selBLineNo" :auto-viewport="true" :select-first-result="true" :location="location" />
            <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :auto-location="true" :show-address-bar="true" />
          </baidu-map>
        </el-skeleton>
      </el-col>

      <el-col :xs="{span: 24}" :sm="{span: 24}" :md="{span: 8}" :lg="{span: 8}" :xl="{span: 8}">
        <el-card shadow="hover" style="margin-bottom: 30px">
          <div slot="header" class="clearfix">
            <span style="font-weight: bold">天气预报</span>
          </div>
          <el-skeleton :loading="loading" :rows="6" animated>
            <el-row :gutter="20">
              <el-col :xs="{span: 10}" :sm="{span: 10}" :md="{span: 10}" :lg="{span: 8}" :xl="{span: 8}">
                <skycon v-if="weather.canvas !== null" :condition="weather.canvas" color="grey" size="128" speed="3" />
              </el-col>
              <el-col :xs="{span: 14}" :sm="{span: 14}" :md="{span: 14}" :lg="{span: 16}" :xl="{span: 16}">
                <div style="position:relative; text-align: center;">
                  <div>
                    <span>当前城市：</span>
                    <span>{{ weather.city }}</span>
                  </div>
                  <div style="padding-top:15px;">
                    <span>天气：</span>
                    <span>{{ weather.type }}</span>
                  </div>
                  <div style="padding-top:15px;">
                    <span>温度：</span>
                    <span>{{ weather.wendu }}°C</span>
                  </div>
                  <div style="padding-top:15px;">
                    <span>{{ weather.desc }}</span>
                  </div>
                  <div style="padding-top:15px;">
                    <span>湿度：</span>
                    <span>{{ weather.shidu }}</span>
                  </div>
                  <div style="padding-top:15px;">
                    <span>PM2.5：</span>
                    <span>{{ weather.pm25 }}</span>
                  </div>
                  <div style="padding:15px 0 15px 0;">
                    <span>空气质量：</span>
                    <span>{{ weather.quality }}</span>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-skeleton>
        </el-card>

        <el-card shadow="hover" style="margin-bottom: 30px">
          <el-skeleton :loading="loading" :rows="3" animated>
            <line-chart :chart-data="weather.chartData" />
          </el-skeleton>
        </el-card>

        <el-card shadow="always" style="margin-bottom: 30px">
          <center class="m-b-20">广告位招商(赞助一下)</center>
          <el-row :gutter="20" type="flex" justify="center">
            <el-button type="primary" round @click="handleDoPay">点击进入捐赠页</el-button>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <beautiful-chat
      :participants="chat.participants"
      :titleImageUrl="chat.titleImageUrl"
      :onMessageWasSent="onMessageWasSent"
      :messageList="chat.messageList"
      :newMessagesCount="chat.newMessagesCount"
      :isOpen="chat.isChatOpen"
      :open="openChat"
      :close="closeChat"
      :showEmoji="true"
      :showFile="false"
      :showEdition="true"
      :showDeletion="true"
      :showTypingIndicator="chat.showTypingIndicator"
      :showLauncher="true"
      :showCloseButton="true"
      :colors="colors"
      :alwaysScrollToBottom="chat.alwaysScrollToBottom"
      :disableUserListToggle="false"
      :messageStyling="chat.messageStyling"
      @edit="editMessage"
    >
      <template v-slot:header>
        <img :src="chat.titleImageUrl" class="sc-header--img" width="60px" />
        <div class="sc-header--title enabled">
          {{chat.participants.map(m=>m.name).join(' & ')}}
        </div>
      </template>
    </beautiful-chat>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getAuthenticationHeader } from '@/utils/store'
import Skycon from 'vue-skycons'
import LineChart from '../components/LineChart'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { chatLogin, chatOffline } from '@/api/system/chat'
import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
import BmControl from 'vue-baidu-map/components/controls/Control.vue'
import BmNavigation from 'vue-baidu-map/components/controls/Navigation.vue'
import BmLocalSearch from 'vue-baidu-map/components/search/LocalSearch.vue'
import BmAutoComplete from 'vue-baidu-map/components/others/AutoComplete.vue'
import BmGeolocation from 'vue-baidu-map/components/controls/Geolocation.vue'
import BmBus from 'vue-baidu-map/components/search/Bus.vue'
const htmlparser = require('htmlparser2')

export default {
  name: 'Dashboard',
  components: {
    Skycon, LineChart, BaiduMap, BmControl, BmNavigation, BmAutoComplete, BmLocalSearch, BmGeolocation, BmBus
  },
  data() {
    return {
      loading: true,
      icon: '',
      weather: {
        city: '',
        canvas: null,
        type: '',
        wendu: '',
        desc: '',
        shidu: '',
        pm25: '',
        quality: '',
        chartData: {
          title: '未来一周天气变化',
          legend: [
            { name: '最高气温' },
            { name: '最低气温' }
          ],
          xAxisData: [],
          yAxisLabel: '{value} °C',
          expectedLabel: '最高气温',
          expectedData: [],
          actualLabel: '最低气温',
          actualData: []
        }
      },
      ak: 'Ykv5kItIHoOtTfK7VNkY1E0MbHpwq8Xm',
      center: { lng: 116.404, lat: 39.915 },
      zoom: 15,
      queryData: {
        selBLine: '',
        selBDir: '',
        selBStop: ''
      },
      mapHeight: document.documentElement.scrollHeight - 326,
      selBDirs: [],
      selBStops: [],
      selBLineNo: '',
      location: '北京',
      keyword: '',
      payChannels: [],
      chat: {
        stompClient: undefined,
        participants: [],  // 用户列表
        titleImageUrl: 'static/img/logo.4081163d.png',
        messageList: [],   // 消息列表
        newMessagesCount: 0,
        isChatOpen: false,
        showTypingIndicator: '',  // 当设置为匹配参与者的值时。它显示特定用户的输入指示
        alwaysScrollToBottom: true,
        messageStyling: true
      }
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ]),
    colors() {
      return {
        header: {
          bg: this.$store.state.settings.theme,
          text: '#ffffff'
        },
        launcher: {
          bg: this.$store.state.settings.theme
        },
        messageList: {
          bg: '#ffffff'
        },
        sentMessage: {
          bg: this.$store.state.settings.theme,
          text: '#ffffff'
        },
        receivedMessage: {
          bg: '#eaeaea',
          text: '#222222'
        },
        userInput: {
          bg: '#f4f7f9',
          text: '#565867'
        }
      }
    }
  },
  mounted() {
    this.handleMessage()
    this.init()
    this.$nextTick(() => {
      this.openSocket()
      window.addEventListener('beforeunload', e => this.closeSocket(e))
    })
  },
  methods: {
    getImageSrc(value) {
      return this.$api.getImageSrc(value)
    },
    async init() {
      await Promise.all([this.handleWeatherData()])
      this.loading = false
    },
    handleMessage() {
      const message = this.$route.query.message
      const type = this.$route.query.type || 'success'
      if (message) {
        this.$message({
          type: type,
          message: message
        })
      }
    },
    async handleWeatherData() {
      const response = await this.$http({
        url: `${process.env.VUE_APP_MODULE_ADMIN_API}/public/weather`,
        method: 'get'
      })
      this.weather.city = response.param.today.city
      this.weather.canvas = response.param.today.canvas
      this.weather.type = response.param.today.type
      this.weather.wendu = response.param.today.wendu
      let desc = response.param.today.high + '°C'
      desc += ' ' + response.param.today.low + '°C'
      desc += ' ' + response.param.today.fx
      desc += ' ' + response.param.today.fl
      this.weather.desc = desc
      this.weather.shidu = response.param.today.shidu
      this.weather.pm25 = response.param.today.pm25
      this.weather.quality = response.param.today.quality
      this.weather.chartData.xAxisData = response.param.forecast.category
      this.weather.chartData.expectedData = response.param.forecast.high
      this.weather.chartData.actualData = response.param.forecast.low
    },
    handlerInitMap({ BMap, map }) {

    },
    changeBLine() {
      this.queryData.selBDir = ''
      this.queryData.selBStop = ''
      this.selBDirs = []
      this.selBStops = []
      this.busTimeInfo = ''
      const busNo = this.queryData.selBLine
      if (busNo) {
        this.$http.get(`${process.env.VUE_APP_MODULE_ADMIN_API}/public/bus/dir`, {
          params: {
            'selBLine': busNo
          }
        }).then(response => {
          const doms = htmlparser.parseDOM(response.param)
          doms.forEach(element => {
            this.selBDirs.push({
              label: element.children[0].data,
              value: element.attribs.value
            })
          })
        }).catch(() => {})
      }
    },
    changeBdir() {
      this.$http.get(`${process.env.VUE_APP_MODULE_ADMIN_API}/public/bus/stop`, {
        params: {
          'selBDir': this.queryData.selBDir
        }
      }).then(response => {
        this.selBStops = []
        const doms = htmlparser.parseDOM(response.param)
        this.selBLineNo = this.queryData.selBLine
        doms.forEach(element => {
          this.selBStops.push({
            label: element.children[0].data,
            value: element.attribs.value
          })
        })
      }).catch(() => {})
    },
    changeBStop() {
      this.$refs.busTimeInfo.innerHTML = ''
      this.$http.get(`${process.env.VUE_APP_MODULE_ADMIN_API}/public/bus/time`, {
        params: {
          'selBLine': this.queryData.selBLine,
          'selBDir': this.queryData.selBDir,
          'selBStop': this.queryData.selBStop
        }
      }).then(response => {
        const obj = JSON.parse(response.param)
        this.$refs.busTimeInfo.innerHTML = obj.html
      }).catch(() => {})
    },
    handleDoPay() {
      this.$router.push('/order/donate')
    },
    openSocket() {
      // 参与者列表
      this.chat.participants = [{
        id: 'support',
        name: '智能客服',
        imageUrl: this.$api.getImageSrc('')
      }]
      if (this.chat.stompClient === undefined) {
        const socket = new SockJS(this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/stomp`)
        // 使用STMOP子协议的WebSocket客户端
        this.chat.stompClient = Stomp.over(socket)
        let headers = getAuthenticationHeader()
        let user = this.$store.getters.user
        chatLogin()
        // 连接WebSocket服务端
        this.chat.stompClient.connect(headers, (frame) => {
          this.chat.stompClient.subscribe('/user/' + user.userId + '/chat/getMessage', (event) => {
            let message = JSON.parse(event.body)
            this.chat.newMessagesCount = this.chat.newMessagesCount + 1
            this.chat.messageList = [ ...this.chat.messageList, {
              type: message.type,
              author: message.sender,
              data: {
                text: message.content
              }
            } ]

            if (this.chat.isChatOpen) {
              this.chat.newMessagesCount = 0
            }
          }, headers)
        }, e => {})
      }
    },
    closeSocket() {
      chatOffline()
      this.chat.newMessagesCount = 0
      this.chat.messageList = []
      if (this.chat.stompClient !== undefined) {
        this.chat.stompClient.disconnect()
        this.chat.stompClient = undefined
      }
    },
    openChat() {
      // 打开聊天时调用
      this.chat.isChatOpen = true
      this.chat.newMessagesCount = 0
    },
    closeChat() {
      // 关闭聊天时调用
      this.chat.isChatOpen = false
    },
    onMessageWasSent(message) {
      // 发送消息时调用
      if (message) {
        let text = {
          sender: this.$store.getters.user.userId,
          receiver: 'support',
          type: message.type,
          content: message.data.text
        }

        this.chat.stompClient.send('/app/chat', {}, JSON.stringify(text))
        this.chat.newMessagesCount = this.chat.isChatOpen ? this.chat.newMessagesCount : this.chat.newMessagesCount + 1
        this.chat.messageList = [ ...this.chat.messageList, message ]
      }
    },
    editMessage(message) {
      const m = this.chat.messageList.find(m => m.id === message.id)
      m.isEdited = true
      m.data.text = message.data.text
    }
  }
}
</script>

<style lang="scss">
.dashboard-container {
  padding: 15px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

.map {
  width: 100%;
  height: 300px;
}
.inquiry_header {
  text-align: center;
}
.inquiry_header .inner {
  color: orangered;
}
.inquiry_main {
  text-align: center;
  margin-top: 5px;
}
.inquiry_main ul li div i.busc {
  background: url('') center;
  display: block;
  width: 15px;
  height: 15px;
  background-size: contain;
}
.inquiry_main ul {
  display: inline-flex;
}
.inquiry_main li {
  width: 12px;
  margin-right: 5px;
  list-style:none;
}
.inquiry_footer {
  display: none;
  text-align: center;
  margin-top: 3px;
}
.q_examination {
  margin-left: 25px;
  padding: 10px 10px;
  border: 2px dashed;
}

.sc-chat-window {
  z-index: 1000;
}
.sc-launcher {
  bottom: 50px!important;
  .sc-open-icon {
    bottom: 50px!important;
  }
  .sc-closed-icon {
    bottom: 50px!important;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
